package com.molyfun.parents.utils;

import android.text.TextUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by ligang on 2017/6/22 0022.
 */

public class StringTagUtils {

    private static final Pattern hashtagPattern = Pattern.compile("#[^#]+#");

    /**
     * 不包含#标签
     * @param originalString
     * @return
     */
    public static List<String> getHashtags(String originalString) {
        List<String> hashtagSet = new ArrayList<String>();
        Matcher matcher = hashtagPattern.matcher(originalString);
        while (matcher.find()) {
            int matchStart = matcher.start();
            int matchEnd = matcher.end();
            String tmpHashtag = originalString.substring(matchStart, matchEnd);
            hashtagSet.add(tmpHashtag.substring(1, tmpHashtag.length() - 1));
            originalString = originalString.substring(matchEnd, originalString.length());
            matcher = hashtagPattern.matcher(originalString);
        }
        return hashtagSet;
    }

    /**
     * 包含#标签
     * @param originalString
     * @return
     */
    public static List<String> getTextList(String originalString) {
        List<String> hashtagSet = new ArrayList<>();
        Matcher matcher = hashtagPattern.matcher(originalString);
        while (matcher.find()) {
            int matchStart = matcher.start();
            int matchEnd = matcher.end();
            if (matchStart != 0) {
                hashtagSet.add(originalString.substring(0, matchStart));
            }
            String tmpHashtag = originalString.substring(matchStart, matchEnd);
            hashtagSet.add(tmpHashtag.substring(0, tmpHashtag.length()));
            originalString = originalString.substring(matchEnd, originalString.length());
            matcher = hashtagPattern.matcher(originalString);
        }
        if (!TextUtils.isEmpty(originalString)) {
            hashtagSet.add(originalString);
        }
        return hashtagSet;
    }


    /**
     * 查找src中find字符串的个数
     * @param src
     * @param find
     * @return
     */
    public static int getOccur(String src, String find) {
        int o = 0;
        int index = -1;
        while ((index = src.indexOf(find, index)) > -1) {
            ++index;
            ++o;
        }
        return o;
    }

}
